<template>
  <div class="login">
    <el-form ref="loginForm" :model="formData" :rules="rules" class="login-form">
      <h3 class="title">注 册</h3>
      <el-form-item prop="email">
        <el-input
          ref="email"
          v-model="formData.email"
          type="text"
          placeholder="邮箱"
          tabindex="1"
          auto-complete="off"
        >
          <template v-slot:prefix>
            <svg-icon icon-class="email" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input
          v-model="formData.code"
          placeholder="验证码"
          style="width: 63%"
          tabindex="2"
          auto-complete="off"
        >
          <template v-slot:prefix>
            <svg-icon icon-class="safety-certificate" class="el-input__icon input-icon" />
          </template>
        </el-input>
        <div class="login-code">
          <el-button
            :loading="sending"
            :disabled="sendDisabled"
            size="small"
            type="primary"
            style="width:100%;"
            @click="handleSendSms"
          >
            {{ sendButtonText }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item prop="username">
        <el-input
          ref="username"
          v-model="formData.username"
          type="text"
          placeholder="账号"
          tabindex="3"
          auto-complete="off"
        >
          <template v-slot:prefix>
            <svg-icon icon-class="user" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="name">
        <el-input
          ref="name"
          v-model="formData.name"
          type="text"
          placeholder="姓名"
          tabindex="4"
          auto-complete="off"
        >
          <template v-slot:prefix>
            <svg-icon icon-class="name1" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          :key="passwordType"
          ref="password"
          v-model="formData.password"
          :type="passwordType"
          placeholder="密码"
          tabindex="5"
          auto-complete="off"
        >
          <template v-slot:prefix>
            <svg-icon icon-class="password" class="el-input__icon input-icon" />
          </template>
          <template v-slot:suffix>
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" class="el-input__icon input-icon" @click="showPwd1" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="checkPass">
        <el-input
          :key="checkPassType"
          ref="checkPass"
          v-model="formData.checkPass"
          :type="checkPassType"
          placeholder="确认密码"
          tabindex="6"
          auto-complete="off"
        >
          <template v-slot:prefix>
            <svg-icon icon-class="check_password" class="el-input__icon input-icon" />
          </template>
          <template v-slot:suffix>
            <svg-icon :icon-class="checkPassType === 'password' ? 'eye' : 'eye-open'" class="el-input__icon input-icon" @click="showPwd2" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="mobile">
        <el-input
          ref="mobile"
          v-model="formData.mobile"
          type="text"
          placeholder="手机号"
          tabindex="7"
          auto-complete="off"
        >
          <template v-slot:prefix>
            <svg-icon icon-class="mobile" class="el-input__icon input-icon" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width:100%;"
          @click.native.prevent="handleRegister"
        >
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <div style="float: right;">
          <router-link class="link-type" :to="'/login'">去登录</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2024 flying All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
// import { getCodeImg } from "@/api/login";
// import Cookies from "js-cookie";
// import { encrypt, decrypt } from '@/utils/jsencrypt'

import { validUsername, validEmail, validMobile } from '@/utils/validate'
import Cookies from 'js-cookie'
import { register, sendCode } from '@/api/user'
import moment from 'moment/moment'

export default {
  name: 'Register',
  components: {},
  data() {
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('请输入正确的邮箱！'))
      } else {
        callback()
      }
    }
    const validateMobile = (rule, value, callback) => {
      if (!validMobile(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validateUsername = (rule, value, callback) => {
      if (!validUsername(value)) {
        callback(new Error('请输入正确的用户！'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码至少6个字符！'))
      } else {
        callback()
      }
    }
    return {
      codeUrl: '',
      formData: {
        email: '',
        code: '',
        username: '',
        name: '',
        password: '',
        checkPass: '',
        mobile: ''
      },
      rules: {
        email: [{ required: true, trigger: 'blur', validator: validateEmail }],
        code: [{ required: true, trigger: 'blur', message: '验证码不能为空' }],
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        checkPass: [{ required: true, trigger: 'blur', message: '确认密码不能为空' }],
        mobile: [{ required: true, trigger: 'blur', validator: validateMobile }]
      },
      sending: false,
      // 发送验证码点击后60s不能重复操作
      sendDisabled: false,
      // 定时
      timer: 0,
      // 密码框展示类型，密码还是文本
      passwordType: 'password',
      checkPassType: 'password',
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {}
    }
  },
  computed: {
    sendButtonText() {
      if (this.timer === 0) {
        return '发送验证码'
      } else {
        return `${this.timer}秒后重发`
      }
    }
  },
  watch: {
    timer(num) {
      if (num > 0) {
        setTimeout(() => {
          this.timer = --num
        }, 1000)
      }
    }
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
    const lastSendTime = Cookies.get('last-send-time')
    if (lastSendTime) {
      const timer = 60 - moment().diff(moment(lastSendTime).format('YYYY-MM-DD HH:mm:ss'), 'seconds')
      this.timer = timer > 0 ? timer : 0
    }
  },
  mounted() {
    // if (this.formData.email === '') {
    //   this.$refs.email.focus()
    // } else if (this.formData.password === '') {
    //   this.$refs.password.focus()
    // }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    handleSendSms() {
      this.$refs.loginForm.validateField(['email'], (errorMessage) => {
        if (!errorMessage) {
          this.sending = true
          const { email } = this.formData
          sendCode({ username: email })
            .then(() => {
              this.$message.success('验证码发送成功，请注意查收!')
              Cookies.set('last-send-time', new Date())
              this.timer = 60
            })
            .finally(() => (this.sending = false))

          Cookies.set('last-send-time', moment().format('YYYY-MM-DD HH:mm:ss'))
          this.timer = 60
        } else {
          console.error('校验失败：' + errorMessage)
          return false
        }
      })
    },
    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd1() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    showPwd2() {
      if (this.checkPassType === 'password') {
        this.checkPassType = ''
      } else {
        this.checkPassType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.checkPass.focus()
      })
    },
    handleRegister() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          delete this.formData.checkPass
          register(this.formData).then(() => {
            this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
            this.loading = false
          })
            .catch(() => {
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../../assets/images/login-background3.jpg");
  background-color: #0fc3ee;
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
</style>
